import { useCallback, useRef } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { useNavigationProps } from '../../types/uses/useNavigation'
// import nutrition from './../pages/nutrition'
//  使用示例

// const Test = () => {
// 	const navigation = useNavigation()
// 	navigation.push('pages/nutrition/x', {
// 		name: '',
// 		age: ''
// 	})
// }

const TIMEOUT_INTERVAL = 5000; // 跳转超时时间

const useNavigation = (props?: useNavigationProps) => {
  const dbClickRef = useRef(false); //防双击操作
  const passTimeRef = useRef<number>(0);
  useDidShow(() => {
    dbClickRef.current = false;
  });
  const formateParams = (o: {}) => {
    if (!o) {
      return "";
    }
    let params = "";
    for (let k in o) {
      if (typeof o[k] === "object") {
        //参数有对象时，先转为字符串，后url编码
        //页面获取对象参数时，先url解码，后解析为对象
        params += `&${k}=${encodeURI(JSON.stringify(o[k]))}`;
      } else {
        params += `&${k}=${o[k]}`;
      }
    }
    params = params.replace(/&/, "?");

    // encodeURI(params)
    return params;
  };

  const push = useCallback((path: string, o?: any): Promise<any> => {
    const nowTime = new Date().getTime();
    if (dbClickRef.current) {
      // 与上次操作间隔时间
      const interval = nowTime - passTimeRef.current;
      if (interval < TIMEOUT_INTERVAL) {
        // 未超过超时时间，则丢弃
        return Promise.reject({ code: 1000, errMsg: "操作过于频繁!" });
      }
    }
    passTimeRef.current = nowTime;
    dbClickRef.current = true;
    const pages = {};
    const addr = path.indexOf("/") === -1 ? pages[path] : path;
    return new Promise((resolve, reject) => {
      const url = addr + formateParams(o);
      Taro.navigateTo({
        url,
        success: resolve,
        fail: res => {
          dbClickRef.current = false;
          reject(res);
        }
      });
    });
  }, []);
  const redirectTo = useCallback((path: string, o?: any): Promise<any> => {
    const pages = {};
    const addr = path.indexOf("/") === -1 ? pages[path] : path;
    return new Promise((resolve, reject) => {
      const url = addr + formateParams(o);
      Taro.redirectTo({
        url,
        success: resolve,
        fail: reject
      });
    });
  }, []);

  const pop = useCallback((delta?: number): Promise<any> => {
    if (Taro.getCurrentPages().length < 2) {
      return new Promise((resolve, reject) => {
        Taro.reLaunch({
          url: props && props.popPath ? props.popPath : "/pages/index/index",
          success: resolve,
          fail: reject
        });
      });
    }
    return new Promise((resolve, reject) => {
      Taro.navigateBack({
        delta: delta ? delta : 1,
        success: resolve,
        fail: reject
      });
    });
  }, []);

  return { push, pop, redirectTo };
};

export default useNavigation;
